package com.icat.house.model;

import java.util.List;
import java.util.UUID;

import com.icat.house.common.DateUtil;
import com.icat.house.common.EncryptionUtil;
import com.jfinal.ext.plugin.tablebind.TableBind;
import com.jfinal.kit.HashKit;
import com.jfinal.kit.StrKit;

@TableBind(tableName = "user_info")
public class UserInfo extends BaseModel<UserInfo> {

	private static final long serialVersionUID = 1L;
	public static final UserInfo dao = new UserInfo();

	/**
	 * 保存
	 * 
	 * @param nickName
	 * @param password
	 * @param phone
	 * @param id_card
	 * @param portrait
	 * @return
	 */
	public boolean save(String nickName, String password, String phone, String id_card, String portrait, int status) {
		UserInfo info = new UserInfo();
		info.set("nick_name", nickName);
		info.set("password", HashKit.md5(password));
		info.set("phone", phone);
		info.set("id_card", id_card);
		UUID uuid = UUID.randomUUID();
		String guid = EncryptionUtil.encryptionAdd(uuid.toString());
		info.set("guid", guid);
		info.set("token", HashKit.md5(guid));
		info.set("token_validity", DateUtil.getDate(7));
		info.set("portrait", null);
		info.set("status", status);
		return info.save();
	}

	/**
	 * 验证登录
	 * 
	 * @param idCard
	 * @param password
	 * @return
	 */
	public UserInfo isUser(String idCard, String password) {
		return findFirst("select * from user_info where id_card = ? and password = ? ", idCard, HashKit.md5(password));
	}

	/**
	 * 验证token
	 * 
	 * @param token
	 * @return
	 */
	public static final UserInfo validateToken(String token) {
		UserInfo info = null;
		if (StrKit.notBlank(token)) {
			info = dao.findFirst("select * from user_info where token = ? and now() <= token_validity",
					HashKit.md5(token));
			if (StrKit.notNull(info)) {
				info.set("token_validity", DateUtil.getDate(7));
				info.update();
			}
		}
		return info;
	}

	public List<UserInfo> userList(int status, String code) {
		return dao.find(
				"select id,nick_name,phone,id_card,status,create_date from user_info where `status` = ? and (nick_name LIKE '%"
						+ code + "%' or id_card LIKE '%" + code + "%')",
				status);
	}

	public UserInfo getUserInfo(String id_card, String phone) {
		return dao.findFirst("select id,password from user_info where id_card =? and phone =? ", id_card, phone);
	}
}
